'''
Created on 29/09/2011

@author: Ike-kun <ragnell22@gmail.com>
'''

from xml.dom import minidom
import csv

class Reader(object):
    def __init__(self, logViewer):
        self.percentRatio = 0.03
        self.logViewer = logViewer

    def readCSV(self,fileName,maxLogDisplay):
        self.logViewer.editTextArea("Reading CSV")
        data = []
        counter = 0
        with open(fileName,"rb") as f:
            reader = csv.reader(f)
            for row in reader:
                for item in row:
                    data.append(item)
                if(counter == maxLogDisplay):
                    break
                counter = counter + 1
        self.logViewer.editTextArea("Done Reading\nCreating Table...")
        return data

    def readXML(self,fileName,maxLogDisplay):
        self.logViewer.editTextArea("Reading XML")
        if(maxLogDisplay > 500):
            maxLogDisplay = 500
        data = []
        doc = minidom.parse(fileName)
        items = doc.getElementsByTagName("item")
        for i in range(len(items)):
            data.append(doc.getElementsByTagName("time")[i].firstChild.nodeValue.strip())
            data.append(doc.getElementsByTagName("priority")[i].firstChild.nodeValue.strip())
            data.append(doc.getElementsByTagName("category")[i].firstChild.nodeValue.strip())
            data.append(doc.getElementsByTagName("NDC")[i].firstChild.nodeValue.strip())
            data.append(doc.getElementsByTagName("message")[i].firstChild.nodeValue.strip())
            if(int(maxLogDisplay * self.percentRatio) == i):
                self.logViewer.editTextArea(str(int(self.percentRatio * 100)) + "% completed")
                self.percentRatio = self.percentRatio + 0.03
            if(i == maxLogDisplay):
                break
        self.logViewer.editTextArea("Done Reading\nCreating Table...")
        return data
